package com.butuh.uang.tuh.ang.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.butuh.uang.tuh.ang.model.EventDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import cn.droidlover.xdroidmvp.log.XLog;

public class DownLoadUtil {


    private static String googlePlayPageName = "com.android.vending";
    private static String googleChromePageName = "com.android.chrome";

    public static void download(Activity context, String yemianName, String djArea, int index, int bianhao, int pattern, int openModel, String url, String pageName) {
        XLog.e("==pattern==" + pattern);
        XLog.e("==openModel==" + openModel);
        XLog.e("==url==" + url);
        XLog.e("==pageName==" + pageName);
        XLog.e("==productId==" + bianhao);
//        //判断是否安装app
//        onClickLog(context, yemianName, djArea, String.valueOf(index), String.valueOf(bianhao));
        String uuid = RandomUtil.getUUID1();
        List<String> maps = new ArrayList<>();
        maps.add(uuid);
        maps.add(yemianName);
        maps.add(djArea);
        maps.add(String.valueOf(index));
        if (checkAppInstalled(context, pageName)) {
            XLog.e("已安装");
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(pageName);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else {
            XLog.e("未安装");
            if (pattern == 1) {
//跳转GP下载
                downloadForPatternGP(context, openModel, url, uuid, bianhao);
            } else {
//apk链接
                downloadForPatternApk(context, openModel, url, uuid, bianhao);
            }
        }
    }


    /***
     * 链接为GP
     * @param context
     * @param openModel
     * @param url
     */
    private static void downloadForPatternGP(Activity context, int openModel, String url, String uuid, int bianhao) {
        if (containPlayOrMarket(url)) {
            //包含Store或者Marker
            if (checkInstalledGooglePlay(context)) {
                //安装了GooglePlay
                if (containPlay(url)) {
                    //包含Store
                    toGooglePlay(context, url.replace("https://play.google.com/store/apps", "market:/"), uuid, bianhao,openModel);
                } else {
                    toGooglePlay(context, url, uuid, bianhao,openModel);
                }
            } else {
                //没有安装GooglePlay
                if (checkInstalledGoogleChrome(context)) {
                    //安装了Google浏览器
                    if (containMarket(url)) {
                        toGoogleChrome(context, url.replace("market:/", "https://play.google.com/store/apps"), uuid, bianhao,openModel);
                    } else {
                        toGoogleChrome(context, url, uuid, bianhao,openModel);
                    }
                } else {
                    //没有安装Google浏览器
                    if (containMarket(url)) {
                        toDefaultChrome(context, url.replace("market:/", "https://play.google.com/store/apps"), uuid, bianhao,openModel);
                    } else {
                        toDefaultChrome(context, url, uuid, bianhao,openModel);
                    }
                }
            }
        } else {
            //不包含Store或者Marker
            if (openModel == 2) {
                //优化 调取重定向  获取真实链接 成功在App中下载 失败 - 调用浏览器下载
                new redirectUrlAsyncTask(context, 0, url, uuid, bianhao,openModel).execute();
            } else {
                //不优化 调用浏览器下载
                if (checkInstalledGoogleChrome(context)) {
                    toGoogleChrome(context, url, uuid, bianhao,openModel);
                } else {
                    toDefaultChrome(context, url, uuid, bianhao,openModel);
                }
            }

        }
    }


    /***
     * 链接为APK
     * @param context
     * @param openModel
     * @param url
     */
    private static void downloadForPatternApk(Activity context, int openModel, String url, String uuid, int bianhao) {
        if (openModel == 2) {
            //优化 调取重定向  获取真实链接 成功在App中下载 失败 - 调用浏览器下载
            new redirectUrlAsyncTask(context, 1, url, uuid, bianhao,openModel).execute();
        } else {
            //不优化 调用浏览器下载
            if (checkInstalledGoogleChrome(context)) {
                //安装了谷歌浏览器 跳转google浏览器下载
                toGoogleChrome(context, url, uuid, bianhao,openModel);
            } else {
                //没有安装谷歌浏览器 跳转默认浏览器下载
                toDefaultChrome(context, url, uuid, bianhao,openModel);
            }
        }
    }


    /***
     * 跳转到Google浏览器
     * @param context
     * @param url
     */
    private static void toGoogleChrome(Context context, String url, String uuid, int bianhao, int openModel) {
        onClickLogEve(context, uuid, url, bianhao,openModel);
        XLog.e("====谷歌浏览器下载====" + url);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setPackage(googleChromePageName);
        intent.setData(Uri.parse(url));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    /***
     * 跳转到系统浏览器
     * @param context
     * @param url
     */
    private static void toDefaultChrome(Context context, String url, String uuid, int bianhao, int openModel) {
        XLog.e("====系统浏览器下载====" + url);
        XLog.e("====UUID======" + RandomUtil.getUUID1());
        onClickLogEve(context, uuid, url, bianhao,openModel);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    /***
     * 跳转到GP
     * @param context
     * @param url
     */
    private static void toGooglePlay(Context context, String url, String uuid, int bianhao, int openModel) {
        XLog.e("====谷歌Play下载====" + url);
        onClickLogEve(context, uuid, url, bianhao,openModel);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setPackage(googlePlayPageName);
        intent.setData(Uri.parse(url));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    private static void onClickLogEve(Context context, String uuid, String url, int bianhao, int openModel) {
        List<String> maps = new ArrayList<>();
        maps.add(uuid);
        maps.add(url);
        if (openModel == 2) {
            //hang-out-one-s-shingle
            OnClickLogUtils.onClickLog(context, "permute", JsonUtils.getRequestBody(maps), bianhao);
            OnClickLogUtils.onClickLog(context, "hang-out-one-s-shingle", JsonUtils.getRequestBody(maps), bianhao);
        } else {
            OnClickLogUtils.onClickLog(context, "permute", JsonUtils.getRequestBody(maps), bianhao);
        }

    }

    public static boolean checkAppInstalled(Context context, String pkgName) {
        if (pkgName == null || pkgName.isEmpty()) {
            return false;
        }
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(pkgName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            return false;
        } else {
            return true;//true为安装了，false为未安装
        }
    }


    /***
     * 判断是否安装googlePlay
     * @param context
     * @return
     */
    private static boolean checkInstalledGooglePlay(Context context) {
        return checkAppInstalled(context, googlePlayPageName);
    }


    /***
     * 判断是否安装google浏览器
     * @param context
     * @return
     */
    private static boolean checkInstalledGoogleChrome(Context context) {
        return checkAppInstalled(context, googleChromePageName);
    }

    /***
     * 判断是否包含"https://play.google.com/store/apps"或"market:/"
     * @param url
     * @return
     */
    private static boolean containPlayOrMarket(String url) {
        if (url.contains("https://play.google.com/store/apps") || url.contains("market:/")) {
            return true;
        }
        return false;
    }

    /***
     * 判断是否包含"https://play.google.com/store/apps"
     * @param url
     * @return
     */
    private static boolean containPlay(String url) {
        if (url.contains("https://play.google.com/store/apps")) {
            return true;
        }
        return false;
    }


    /***
     * 判断是否包含"market:/"
     * @param url
     * @return
     */
    private static boolean containMarket(String url) {
        if (url.contains("market:/")) {
            return true;
        }
        return false;
    }


    private static class redirectUrlAsyncTask extends AsyncTask<String, String, String> {

        int type;
        Activity context;
        String url;
        String uuid;
        int bianhao;
        int openModel;

        public redirectUrlAsyncTask(Activity context, int type, String url, String uuid, int bianhao,int openModel) {
            this.context = context;
            this.type = type;
            this.url = url;
            this.uuid = uuid;
            this.bianhao = bianhao;
            this.openModel = openModel;
        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... strings) {
            return getRedirectUrl(url);
        }

        @Override
        protected void onPostExecute(final String path) {
            super.onPostExecute(path);
            XLog.e("==重定向URL==" + path);
            if (type == 1) {
                if (!TextUtils.isEmpty(path)) {
                    XLog.e("--在APP内部下载--");
                    new AlertDialog.Builder(context).setTitle("是否开始下载?").setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            downloadApk(context, path);
                            onClickLogEve(context, uuid, url, bianhao,openModel);
                        }
                    }).setNegativeButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();

                } else {
                    if (checkInstalledGoogleChrome(context)) {
                        toGoogleChrome(context, path, uuid, bianhao,openModel);
                    } else {
                        toDefaultChrome(context, path, uuid, bianhao,openModel);
                    }
                }
            } else {
                if (!TextUtils.isEmpty(path)) {
                    //转换成功
                    if (checkInstalledGooglePlay(context)) {
//安装了GooglePlay
                        if (containPlay(path)) {
                            //包含store
                            toGooglePlay(context, path.replace("https://play.google.com/store/apps", "market:/"), uuid, bianhao,openModel);
                        } else {
                            toGooglePlay(context, path, uuid, bianhao,openModel);
                        }
                    } else {
                        //没有安装GooglePlay
                        if (checkInstalledGoogleChrome(context)) {
                            //安装了Google浏览器
                            if (containMarket(path)) {
                                toGoogleChrome(context, path.replace("market:/", "https://play.google.com/store/apps"), uuid, bianhao,openModel);
                            } else {
                                toGoogleChrome(context, path, uuid, bianhao,openModel);
                            }
                        } else {
                            //使用默认浏览器
                            if (containMarket(path)) {
                                toDefaultChrome(context, path.replace("market:/", "https://play.google.com/store/apps"), uuid, bianhao,openModel);
                            } else {
                                toDefaultChrome(context, path, uuid, bianhao,openModel);
                            }
                        }
                    }
                } else {
                    //转换失败
                    if (checkInstalledGoogleChrome(context)) {
                        //安装了Google浏览器
                        if (containMarket(url)) {
                            toGoogleChrome(context, url.replace("market:/", "https://play.google.com/store/apps"), uuid, bianhao,openModel);
                        } else {
                            toGoogleChrome(context, url, uuid, bianhao,openModel);
                        }
                    } else {
                        //使用默认浏览器
                        if (containMarket(url)) {
                            toDefaultChrome(context, url.replace("market:/", "https://play.google.com/store/apps"), uuid, bianhao,openModel);
                        } else {
                            toDefaultChrome(context, url, uuid, bianhao,openModel);
                        }
                    }
                }
            }

        }
    }

    private static AppDownloadManager mDownloadManager;


    public static void downloadApk(Activity context, String url) {
        EventBus.getDefault().post(new EventDialog());
        if (null == mDownloadManager) {
            mDownloadManager = new AppDownloadManager(context);
        }
        mDownloadManager.downloadApk(url, "下载中");
    }


    /**
     * 获取重定向地址
     *
     * @param path
     * @return
     * @throws Exception
     */
    private static String getRedirectUrl(String path) {
        XLog.e("=====重定向之前=====" + path);
        String url = null;
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setConnectTimeout(5000);
            url = conn.getHeaderField("Location");
            conn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }


}
